package com.ehais.modbuswifi;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.ehais.adapter.NewScanBatteryAdapter;
import com.ehais.analysis.Phosphoric;
import com.ehais.analysis.Plumbic;
import com.ehais.api.ApiRetrofit;
import com.ehais.model.NewScanBatteryData;
import com.ehais.model.StationInfo;
import com.ehais.model.StationResult;
import com.ehais.util.AsciiToHex;
import com.ehais.util.OnRequestBack;
import com.ehais.util.SocketManager;
import com.ehais.util.WifiApUtil;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


import android.app.AlertDialog;
import android.content.DialogInterface;


import android.view.KeyEvent;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;


public class NewScanActivity extends AppCompatActivity {
    Integer indexTmp = 0;
    private static final String TAG="WifiUtil";
    boolean sConnect = true;//socket是否建立连接Connect
    private String category = "Phosphoric";
    private int frequencyTimerPlumbic = 2000;//铅酸定时采集频率10秒
    private int quickFrequencyTimerPhosphoricAcid = 1000;//锂电定时采集频率1秒
    private int frequencyTimerPhosphoricAcid = 5000;//锂电定时采集频率1秒


    private long startTime = 0;
//    private long tmpTimerSubmit = 0;//临时赋值

    private Button btnOpenPlumbicAcid; // 开启铅酸检测
    private Button btnOpenPhosphoricAcid; // 开启磷酸铁锂检测
    private Button btnCloseWifi;
    //    private TextView tvMacWifi;
    private TextView tvCommand;
    private TextView tvSocketServer;
    private ListView batteryListView;
    private TextView current_address;
    private ImageView alarmOnImageView;
    private TextView tvTips;
    private TextView tvSkipAI;
    private OnRequestBack requestBack;
    private long tmpCaptureTime = 0;//采集的临时时间
    private long timeOutCapture = 1000;//超时采集时间

    private Integer versionIndex = 0;
    private Integer sequenceIndex = 0;//命令序号
    private static Integer signalIndex = 0;
    private static Integer manufacturersIndex = 0;
    private String phosphoricType = "measurement";//开始是遥测命令类型
    private String commandIng = "no";
    private static String scanIng = "doing";
    private static String socketConnectStatus = "等待连接";


    private static List<Integer> scanVersions = new ArrayList<Integer>();
    private static List<Integer> scanSignal = new ArrayList<Integer>();
    private static List<Integer> scanManufacturers = new ArrayList<Integer>();

    //    private static JSONArray scanArray = new JSONArray();
    private static JSONObject jsonObject = null;
    private static JSONArray measurementArray = null;
    private Timer timer;
    private Timer sTimer;


    private StationInfo stationResult = null;//new StationInfo();//传递的参数


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_scan);

        //获取上一个页面传入基站对象
        stationResult = (StationInfo) getIntent().getExtras().getSerializable("STATION");

        btnOpenPlumbicAcid = (Button) findViewById(R.id.btnOpenPlumbicAcid);
        btnOpenPhosphoricAcid = (Button) findViewById(R.id.btnOpenPhosphoricAcid);
        batteryListView = (ListView) findViewById(R.id.batteryListView);
//        alarmOnImageView = (ImageView) findViewById(R.id.alarmOnImageView);

        //根据传递过来的参数设置是采集铅/锂，并把另一个按钮隐藏
        category = (String) getIntent().getStringExtra("category");//判断采集的是 铅 Plumbic / 锂 Phosphoric
        if(category.equals("Plumbic")){
            btnOpenPlumbicAcid.setVisibility(View.VISIBLE);
            btnOpenPhosphoricAcid.setVisibility(View.GONE);
        }else if(category.equals("Phosphoric")){
            btnOpenPlumbicAcid.setVisibility(View.GONE);
            btnOpenPhosphoricAcid.setVisibility(View.VISIBLE);
        }

        btnCloseWifi = (Button) findViewById(R.id.btnCloseWifi);

        tvCommand = (TextView) findViewById(R.id.tvCommand);
        tvSocketServer = (TextView) findViewById(R.id.tvSocketServer);
        tvTips = (TextView) findViewById(R.id.tvTips);
        tvSkipAI = (TextView) findViewById(R.id.tvSkipAI);



        try {
            jsonObject = AsciiToHex.getCommandData(this);
            measurementArray = jsonObject.getJSONArray("measurement");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }


        requestBack = new OnRequestBack() {
            @Override
            public void onSuccessPlumbic(String data) { //铅酸
                try{
                    List<NewScanBatteryData> newScanBatteryData = Plumbic.getInstance().success(stationResult,data);
                    refreshResult(stationResult,newScanBatteryData);//实时刷新检测结果
                    Plumbic.getInstance().submit(newScanBatteryData);//定时发送的

                    saveOriginalData("铅酸",data);

                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void onSuccessPhosphoric(String data) {//磷酸铁锂

                try{
                    String _data = data.substring(0,data.length() -4);
                    String _sum = data.substring(data.length() - 4 , data.length());
                    String mySum = AsciiToHex.chksum(_data);
                    Log.i(TAG,"原始校验位  ：" + _sum+"  ； 计算校验位："+mySum);
                    if(mySum.equals(_sum)){
                        //开始计算正式的位置
                        String msg = null;
                        if(scanIng.equals("doing")) {
                            if(scanVersions.indexOf(versionIndex) < 0) {
                                saveOriginalData(measurementArray.getJSONObject(versionIndex).getString("command"),data);
                                //做去重判断，存在0000的，就不要加E020
//                                Log.i(TAG,"当前命令&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&："+measurementArray.getJSONObject(versionIndex).getString("command"));
                                boolean f = true;
                                //判断长度是否超出字符串本身长度，不添加
                                String hex = "0x"+data.substring(17, 19);
                                Integer x = Integer.parseInt(hex.substring(2),16);
                                if((x * 4 + 19) > data.length()) f = false;
                                if(f){
                                    for(int i = 0 ; i < scanVersions.size() ; i++){
//                                    Log.i(TAG,"检验存在的命令&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&："+measurementArray.getJSONObject(scanVersions.get(i)).getString("command"));
                                        if(
                                                (measurementArray.getJSONObject(scanVersions.get(i)).getString("command").substring(0,9)).equals(measurementArray.getJSONObject(versionIndex).getString("command").substring(0,9))
                                                        ||
                                                        ((measurementArray.getJSONObject(scanVersions.get(i)).getString("command").substring(0,5)).equals(measurementArray.getJSONObject(versionIndex).getString("command").substring(0,5)) && (measurementArray.getJSONObject(scanVersions.get(i)).getString("command").substring(7,9)).equals(measurementArray.getJSONObject(versionIndex).getString("command").substring(7,9)))
                                        ){
//                                        Log.i(TAG,"是为重复命令，要去重..........................................................................");
                                            f = false;break;
                                        }
                                    }
                                }

                                if(f){
                                    scanVersions.add(versionIndex);
                                    scanSignal.add(-1);
                                    scanManufacturers.add(-1);
                                    Phosphoric.getInstance().add(stationResult);//stationResult
                                    System.out.println("加入版本："+versionIndex+"  ==>  "+scanVersions.size());
                                    socketConnectStatus = "采集"+scanVersions.size()+"台，时间:";
                                }

                            }
                            versionIndex ++;
                            commandIng = "no";
                        }else if(scanIng.equals("signal")) {//扫描厂家信息
                            scanSignal.set(sequenceIndex, signalIndex);
                            //开始进入下一个的扫描
                            if(sequenceIndex < scanVersions.size() - 1){
                                sequenceIndex ++;
                                signalIndex = 0;
                            }else{
                                scanIng = "manufacturers";
                                sequenceIndex = 0;
                                manufacturersIndex = 0;
                            }
                            commandIng = "no";
                        }else if(scanIng.equals("manufacturers")) {//扫描厂家信息
                            scanManufacturers.set(sequenceIndex, manufacturersIndex);
                            String command = measurementArray.getJSONObject(scanVersions.get(sequenceIndex)).getString("command");
                            Phosphoric.getInstance().manufacturers(data,sequenceIndex,command.substring(3,5),stationResult);
                            //开始进入下一个的扫描
                            commandIng = "no";
                            if(sequenceIndex < scanVersions.size() - 1){
                                sequenceIndex ++;
                                manufacturersIndex = 0;
                            }else{
                                scanIng = "gather";
                                sequenceIndex = 0;
                                manufacturersIndex = 0;
                                phosphoricType = "measurement";//从遥测开始进入
                                Phosphoric.getInstance().initGather();

                                if(timer != null){
                                    timer.cancel();
                                    timer.purge();
                                    timer = null;
                                }
                                timer = new Timer();
                                timer.schedule(getTimerTask(),0,frequencyTimerPhosphoricAcid);

                            }

                        }else if(scanIng.equals("gather")) {
                            if(phosphoricType.equals("measurement")){
                                NewScanBatteryData newScanBatteryData = Phosphoric.getInstance().measurement(data,sequenceIndex);
//                                refreshResult(stationResult,newScanBatteryData);//实时刷新检测结果
                                phosphoricType = "signal";
                                Phosphoric.getInstance().submit();
                            }else if(phosphoricType.equals("signal")) {
                                NewScanBatteryData newScanBatteryData = Phosphoric.getInstance().signal(data,sequenceIndex);
//                                refreshResult(stationResult,newScanBatteryData);
                                phosphoricType = "measurement";
                                sequenceIndex ++;
                                //每隔60秒上传一下数据
                                Phosphoric.getInstance().submit();
                            }
                        }

                    }


                }catch (Exception e){
                    e.printStackTrace();
                }


            }

            @Override
            public void onSConnect() {
                sConnect = true;
                timer = new Timer();

                phosphoricType = "measurement";
                versionIndex = 0;
                sequenceIndex = 0;
                commandIng = "no";
                if(category.equals("Plumbic")){
                    timer.schedule(getTimerTask(), 0, frequencyTimerPlumbic);
                }else if(category.equals("Phosphoric")){
                    timer.schedule(getTimerTask(), 0, quickFrequencyTimerPhosphoricAcid);//先快速匹配
                    tvSkipAI.post(new Runnable() {
                        @Override
                        public void run() {
                            tvSkipAI.setVisibility(View.VISIBLE);
                        }
                    });
                }

                startTime = System.currentTimeMillis();
                socketConnectStatus = "采集时间";
                if(sTimer != null){
                    sTimer.cancel();
                    sTimer.purge();
                    sTimer = null;
                }
                sTimer = new Timer();
                sTimer.schedule(gatherTimer(),0,1000);

            } // socket建立连接成功


            @Override
            public void onFailed(String msg) {

            }
        };

        btnOpenPlumbicAcid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG,"开启热点事件");

                btnOpenPlumbicAcid.setVisibility(View.GONE);
                btnOpenPhosphoricAcid.setVisibility(View.GONE);
                btnCloseWifi.setVisibility(View.VISIBLE);
                tvSocketServer.setVisibility(View.GONE);
//                alarmOnImageView.setVisibility(View.GONE);

                SocketManager.startServer(requestBack,"Plumbic");
                String myIp = WifiApUtil.getIPAddress();
                Log.i(TAG,"本机IP："+myIp);
//                tvLocalMacWifi.setText("本机IP："+myIp);
                category = "Plumbic";

                Plumbic.getInstance().init();

                socketConnectStatus = "采集准备开始，等待设备连接";
                startTime = System.currentTimeMillis();
                if(sTimer != null){
                    sTimer.cancel();
                    sTimer.purge();
                    sTimer = null;
                }
                sTimer = new Timer();
                sTimer.schedule(gatherTimer(),0,frequencyTimerPlumbic);

            }
        });


        btnOpenPhosphoricAcid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG,"开启热点事件");
                btnOpenPlumbicAcid.setVisibility(View.GONE);
                btnOpenPhosphoricAcid.setVisibility(View.GONE);
                btnCloseWifi.setVisibility(View.VISIBLE);
                tvSocketServer.setVisibility(View.VISIBLE);
//                alarmOnImageView.setVisibility(View.GONE);
//                tvSkipAI.setVisibility(View.VISIBLE);
                phosphoricType = "measurement";
                versionIndex = 0;
                sequenceIndex = 0;
                commandIng = "no";

                scanVersions.clear();
                scanSignal.clear();
                scanManufacturers.clear();


                SocketManager.startServer(requestBack,"Phosphoric");
                String myIp = WifiApUtil.getIPAddress();
                Log.i(TAG,"本机IP："+myIp);
//                tvLocalMacWifi.setText("本机IP："+myIp);

                category = "Phosphoric";
                phosphoricType = "measurement";
                scanIng = "doing";

                Phosphoric.getInstance().clear();

                socketConnectStatus = "采集准备开始，等待设备连接";
                startTime = System.currentTimeMillis();
                if(sTimer != null){
                    sTimer.cancel();
                    sTimer.purge();
                    sTimer = null;
                }
                sTimer = new Timer();
                sTimer.schedule(gatherTimer(),0,10000);
            }
        });

        btnCloseWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG,"关闭热点事件");


                AlertDialog.Builder builder = new AlertDialog.Builder(NewScanActivity.this);
                builder.setTitle("提示").setMessage("确定要停止采集数据吗")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                onCloseEvent();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 用户点击取消按钮后的逻辑处理
                            }
                        })
                        .show();

            }
        });

        tvSkipAI.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                scanIng = "signal";//寻址结束，开始搜索遥信信息
                sequenceIndex = 0;
                manufacturersIndex = 0;
                tvSkipAI.setVisibility(View.GONE);
            }
        });



        //开启热点，同时关闭WIFI================================================================================================
        WifiApUtil.requestSystemSetPermissionAndOptionWifiAp(NewScanActivity.this);

    }


    public void refreshResult(StationInfo stationResult,List<NewScanBatteryData> newScanBatteryData){

        batteryListView.post(new Runnable() {
            @Override
            public void run() {
                NewScanBatteryAdapter adapter = new NewScanBatteryAdapter(NewScanActivity.this,R.layout.adapter_new_scan_battery,newScanBatteryData);
                batteryListView.setAdapter(adapter);
                ViewGroup.LayoutParams params = batteryListView.getLayoutParams();
                params.height = adapter.getCount() * 398 + 50;
                batteryListView.setLayoutParams(params);
                batteryListView.requestLayout();
            }
        });



    }

    //采集时间计时器
    public TimerTask gatherTimer(){
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                long time = (System.currentTimeMillis() - startTime) / 1000;
                long hours = time / 3600;
                long minutes = (time % 3600) / 60;
                long seconds = (time % 3600) % 60;
                tvTips.post(new Runnable() {
                    @Override
                    public void run() {
                        tvTips.setText(socketConnectStatus+"  "+(hours < 10 ? '0' : "")+hours+":"+(minutes < 10 ? '0':"")+minutes+":"+(seconds < 10 ? '0':"")+seconds);
                    }
                });
            }
        };
        return timerTask;
    }

    public TimerTask getTimerTask(){
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                // 定时器做的任务放在这里
                if(sConnect){//开启wifi的情况


                    if(category.equals("Plumbic")){//Plumbic
//                        SocketManager.sendMsgAll("00 00 00 00 00 06 01 04 03 E8 00 0A",type);//每一秒不断地发命令
                        SocketManager.sendMsgAll("00 00 00 00 00 06 01 04 03 E8 00 32",category);//每一秒不断地发命令
                    } else if(category.equals("Phosphoric")) {//Phosphoric 磷酸铁锂
                        String msg = null;
                        try{
                            if(scanIng.equals("doing")) {//寻址阶段
//                                Log.i(TAG,"遥测寻址状态:"+scanIng+"    时差："+(System.currentTimeMillis() - tmpCaptureTime)+"  进度："+versionIndex+"/"+measurementArray.length());
                                if(commandIng.equals("yes")) {//正在执行中命令
                                    if((System.currentTimeMillis() - tmpCaptureTime) >= timeOutCapture){//判断超时，以豪秒判断
                                        commandIng = "no";
                                        if(versionIndex < measurementArray.length() - 1) {
                                            versionIndex ++;
                                        }else {
                                            scanIng = "signal";//寻址结束，开始搜索遥信信息
                                            sequenceIndex = 0;
                                            manufacturersIndex = 0;
                                            System.out.println("读取电池数量为：============="+scanVersions.size());
                                        }
                                    }
                                }
                                if(commandIng.equals("no") && scanIng.equals("doing")) {//继续执行寻址命令
                                    tmpCaptureTime = System.currentTimeMillis();
                                    commandIng = "yes";
                                    System.out.println("获取第"+versionIndex+"行命令");
                                    String command = measurementArray.getJSONObject(versionIndex).getString("command");
                                    System.out.println("正在执行的寻址命令是:"+command+" ========>  versionIndex:"+versionIndex);
                                    SocketManager.sendMsgAll(command , category);
                                }
                            }else if(scanIng.equals("signal")) {//扫描遥信的命令

                                if(commandIng.equals("yes")) {//正在执行中命令
                                    if((System.currentTimeMillis() - tmpCaptureTime) >= timeOutCapture){//判断超时，以豪秒判断
                                        commandIng = "no";
                                        if(sequenceIndex < scanVersions.size()) {
                                            String version = measurementArray.getJSONObject(scanVersions.get(sequenceIndex)).getString("version");
                                            JSONObject jsonVersion = jsonObject.getJSONObject(version);
                                            JSONArray signalArray = jsonVersion.getJSONArray("signal");
                                            if(signalIndex < signalArray.length() - 1) {
                                                signalIndex ++;
                                                System.out.println("正在采集遥信的信息……………………sequenceIndex:"+sequenceIndex+"    signalIndex:"+signalIndex);
                                            }else {
                                                if(sequenceIndex < scanVersions.size() - 1) {
                                                    sequenceIndex ++;
                                                    signalIndex = 0;
                                                    System.out.println("继续获取下一份的厂商信息,sequenceIndex:"+sequenceIndex);
                                                }else {
                                                    System.out.println("获取遥信信息结束，进入正式采集==========================================");
                                                    scanIng = "manufacturers";
                                                    sequenceIndex = 0;
                                                    for(int i = 0 ; i < scanSignal.size() ; i++) {
                                                        System.out.println("遥信信息 : "+i + " ============ "+ scanSignal.get(i));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if(commandIng.equals("no") && scanIng.equals("signal")) {
                                    Log.i(TAG,"遥信寻址状态:"+scanIng+"    时差："+(System.currentTimeMillis() - tmpCaptureTime)+"  进度："+sequenceIndex+"/"+scanVersions.size()+"/");
                                    tmpCaptureTime = System.currentTimeMillis();
                                    String version = measurementArray.getJSONObject(scanVersions.get(sequenceIndex)).getString("version");
                                    JSONObject jsonVersion = jsonObject.getJSONObject(version);
                                    JSONArray signalArray = jsonVersion.getJSONArray("signal");
                                    commandIng = "yes";
                                    JSONObject jsonSignal = signalArray.getJSONObject(signalIndex);
                                    String command = jsonSignal.getString("command");
                                    System.out.println(version+"==>正在执行遥信的命令是:"+command+" ========>  sequenceIndex:"+sequenceIndex+"  -->  signalIndex:"+signalIndex);
                                    SocketManager.sendMsgAll(command , category);
                                }
                            }else if(scanIng.equals("manufacturers")) {//扫描厂家信息
                                if(commandIng.equals("yes")) {//正在执行中命令
                                    if((System.currentTimeMillis() - tmpCaptureTime) >= timeOutCapture){//判断超时，以豪秒判断
                                        commandIng = "no";
                                        if(sequenceIndex < scanVersions.size()) {
                                            String version = measurementArray.getJSONObject(scanVersions.get(sequenceIndex)).getString("version");
                                            JSONObject jsonVersion = jsonObject.getJSONObject(version);
                                            JSONArray manufacturersArray = jsonVersion.getJSONArray("manufacturers");
                                            if(manufacturersIndex < manufacturersArray.length() - 1) {
                                                manufacturersIndex ++;
                                                System.out.println("正在采集厂商信息……………………sequenceIndex:"+sequenceIndex+"    manufacturersIndex:"+manufacturersIndex);
                                            }else {
                                                if(sequenceIndex < scanVersions.size() - 1) {
                                                    sequenceIndex ++;
                                                    manufacturersIndex = 0;
                                                    System.out.println("继续获取下一份的厂商信息,sequenceIndex:"+sequenceIndex);
                                                }else {
                                                    System.out.println("获取厂家信息结束，进入正式采集");
                                                    scanIng = "gather";
                                                    phosphoricType = "measurement";//从遥测开始进入
                                                    sequenceIndex = 0;
                                                    Phosphoric.getInstance().initGather();
//                                                    tmpTimerSubmit = System.currentTimeMillis();

                                                    if(timer != null){
                                                        timer.cancel();
                                                        timer.purge();
                                                        timer = null;
                                                    }
                                                    timer = new Timer();
                                                    timer.schedule(getTimerTask(),0,frequencyTimerPhosphoricAcid);

                                                }
                                            }
                                        }
                                    }
                                }
                                if(commandIng.equals("no") && scanIng.equals("manufacturers")) {
                                    tmpCaptureTime = System.currentTimeMillis();
                                    String version = measurementArray.getJSONObject(scanVersions.get(sequenceIndex)).getString("version");
                                    JSONObject jsonVersion = jsonObject.getJSONObject(version);
                                    JSONArray manufacturersArray = jsonVersion.getJSONArray("manufacturers");
                                    commandIng = "yes";
                                    JSONObject jsonManufacturers = manufacturersArray.getJSONObject(manufacturersIndex);
                                    String command = jsonManufacturers.getString("command");
                                    System.out.println(version+"==>正在执行厂家的命令是:"+command+" ========>  sequenceIndex:"+sequenceIndex+"  -->  manufacturersIndex:"+manufacturersIndex);
                                    SocketManager.sendMsgAll(command , category);
                                }

                            }else if(scanIng.equals("gather")) {//正式进入采集
                                if(sequenceIndex >= scanVersions.size()) sequenceIndex = 0;
                                if(phosphoricType.equals("measurement")) {
                                    String command = measurementArray.getJSONObject(scanVersions.get(sequenceIndex)).getString("command");
                                    System.out.println(sequenceIndex+"  正式进入轮循交替采集信息..............遥测........"+command);
                                    SocketManager.sendMsgAll(command , category);
                                }else if(phosphoricType.equals("signal")) {
                                    if(scanSignal.get(sequenceIndex) > -1) {
                                        String version = measurementArray.getJSONObject(scanVersions.get(sequenceIndex)).getString("version");
                                        JSONObject jsonVersion = jsonObject.getJSONObject(version);
                                        String command = jsonVersion.getJSONArray("signal").getJSONObject(scanSignal.get(sequenceIndex)).getString("command");
                                        System.out.println(sequenceIndex+"  正式进入轮循交替采集信息..............遥信........"+command);
                                        SocketManager.sendMsgAll(command , category);
                                    }else {
                                        System.out.println(sequenceIndex + "  当前遥信无数据..............遥信........");
                                        sequenceIndex ++;
                                        phosphoricType = "measurement";
                                    }

                                }
                            }


                            tvSocketServer.post(new Runnable() {
                                @Override
                                public void run() {
                                    try{
                                        if(scanIng.equals("doing")){                                    ;
                                            tvSocketServer.setText("AI扫描："+ measurementArray.getJSONObject(versionIndex).getString("command")+"  进度： " + (versionIndex + 1) +" / "+measurementArray.length() +"" );
                                        } else if(scanIng.equals("signal")){
                                            tvSocketServer.setText("AI检验：" + (signalIndex + 1) + "/" + (sequenceIndex + 1) +" / "+scanVersions.size());
                                        } else if (scanIng.equals("manufacturers")){
                                            tvSocketServer.setText("AI识别：" + (manufacturersIndex + 1) + "/" + (sequenceIndex + 1) +" / "+scanVersions.size());
                                        } else if (scanIng.equals("gather")){
                                            tvSocketServer.setText("");
                                        }
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }

                                }
                            });

                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                }else{
//                    tvModbusBody.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            tvModbusBody.setText("");
//                        }
//                    });
                }
            }
        };
        return timerTask;
    }


    private void onCloseEvent(){
        if(category.equals("Plumbic")){
            btnOpenPlumbicAcid.post(new Runnable() {
                @Override
                public void run() {
                    btnOpenPlumbicAcid.setVisibility(View.VISIBLE);
                }
            });
        }else if(category.equals("Phosphoric")){
            btnOpenPhosphoricAcid.post(new Runnable() {
                @Override
                public void run() {
                    btnOpenPhosphoricAcid.setVisibility(View.VISIBLE);
                }
            });
        }

        btnCloseWifi.post(new Runnable() {
            @Override
            public void run() {
                btnCloseWifi.setVisibility(View.GONE);
            }
        });

        tvSkipAI.post(new Runnable() {
            @Override
            public void run() {
                tvSkipAI.setVisibility(View.GONE);
            }
        });

//                tvMacWifi.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        tvMacWifi.setText("");
//                    }
//                });
        tvSocketServer.post(new Runnable() {
            @Override
            public void run() {
                tvSocketServer.setText("");
            }
        });

//                tvModbusBody.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        tvModbusBody.setText("");
//                    }
//                });




        SocketManager.shutDown();
//        WifiApUtil.closeWifiAp();


        if(timer != null){
            timer.cancel();//取消定时任务
            timer.purge();
            timer = null;
        }

        if(sTimer != null){
            sTimer.cancel();//取消定时任务
            sTimer.purge();
            sTimer = null;
        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
//            Toast.makeText(this,"返回键Back键测试", Toast.LENGTH_SHORT).show();

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示")
                    .setMessage("确定要退出采集数据吗")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            onCloseEvent();
                            onBackPressed();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 用户点击取消按钮后的逻辑处理
                        }
                    })
                    .show();

        }

        return false;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }



    public void saveOriginalData(String command,String data){//保留原始数据
        if(ApiRetrofit.debug) return ;
//        Map<String, String> paramas = new HashMap<String, String>();
//        paramas.put("command",command);
//        paramas.put("data",data);
//        ApiService apiService= ApiRetrofit.getApiRetrofit().getApiService();
//        Observable<Result> observable = apiService.saveOriginalData(paramas);
//
//        Subscriber subscriber=new Subscriber<String>() {
//            @Override
//            public void onCompleted() {
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                e.printStackTrace();
//            }
//
//            @Override
//            public void onNext(String o) {
//            }
//        };
//        observable.subscribe(subscriber);
    }



}